"""ticket URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
import time

from django.conf.urls import url
from django.contrib import admin
from django.urls import path, include
from userInformation.views import *
from flight.views import *
from ticket import *
from django.views.generic.base import TemplateView
from flight.models import *
from apscheduler.schedulers.background import BackgroundScheduler
import requests

from threading import Lock, Thread
from functools import wraps

default_lock = Lock()
lock_list = {'default': Lock()}


def synchronized(func=None, obj=None):
    if func is not None:
        @wraps(func)
        def wrapper(*args, **kwargs):
            lock = lock_list['default']
            lock.acquire()
            try:
                return func(*args, **kwargs)
            finally:
                lock.release()

        return wrapper
    if obj is not None:
        cur_id = id(obj)
        default_lock.acquire()
        try:
            current_lock = lock_list.get(id(obj), None)
            if current_lock is None:
                current_lock = Lock()
                lock_list[cur_id] = current_lock
        finally:
            default_lock.release()

        def decorator(func):
            def wrapper(*args, **kwargs):
                current_lock.acquire()
                try:
                    return func(*args, **kwargs)
                finally:
                    current_lock.release()

            return wrapper

        return decorator


a = 0
obj = []

now = timezone.now()
@synchronized(obj=obj)
def timedTaskCredit():
    # 更新信用信息

    now = timezone.now()
    now = str(now).split(' ')[0]
    delta = timedelta(days=30)
    users = UserInfo.objects.all()
    for user in users:
        records = RefondRecord.objects.filter(userId=user.userId)
        recent_records = []

        for record in records:

            if record.date + delta.__ge__(now):
                recent_records.append(record)

        if len(recent_records) == 0:
            user.creditLevel = 1
            user.save()
    return


@synchronized(obj=obj)
def timedTaskChangeFlightStatus():
    now = timezone.now()
    now = str(now).split('.')[0]
    flights = FlightInfo.objects.all()
    for flight in flights:

        if flight.state < 0:
            continue
        if now.__ge__(str(flight.dseatTime).split('.')[0]):
            flight.state = 2
        if now.__ge__(str(flight.dboardingTime).split('.')[0]):
            flight.state = 3
        if now.__ge__(str(flight.startTime).split('.')[0]):
            flight.state = 4
        flight.save()
    return


scheduler = BackgroundScheduler()
scheduler.add_job(timedTaskCredit, 'interval', seconds=24 * 60 * 60)
scheduler.add_job(timedTaskChangeFlightStatus, 'interval', seconds= 30)
scheduler.start()

urlpatterns = [
    path('', home, name='home'),
    path('register/', register, name='register'),
    path('admin/', admin.site.urls),
    path('login/', login, name='login'),
    path('admin/', admin.site.urls),
    path('book/', searchFlight, name='searchflight'),
    path('bookticket/', bookticket, name='bookticket'),
    path('delay/', delay, name='delay'),
    path('check_in/', check_in, name='check_in'),
    path('refund/', refund, name='refund'),
    path('endorse/', endorse, name='endorse'),
    path('search/', searchFlight, name='searchFlight'),
    path('print/', printTicket, name='printTicket'),
    path('Admin/', include('adminpage.urls')),
    path('getState/', getState, name='getState'),
    path('list/', listtickets, name='list'),
    path('gcity/', getCity, name='gcity'),
    path('getseat/', getSeatlist, name='getseat')
]
